package com.iengoo.spacewar;

import java.util.concurrent.LinkedBlockingDeque;

/**
 * @author zpym
 * @CopyRight (C) http://www.iengoo.com
 * @brief 存放子弹的队列
 * @email 122162005@qq.com
 * @date 2018-12-26 13:45
 */
public class MessageQueue {
    private static LinkedBlockingDeque<Object> queue;
    private int size;

    public int length;
    public static MessageQueue instance = new MessageQueue(30);

    public MessageQueue() {
        this.size = 20;
        queue = new LinkedBlockingDeque<>(this.size);
    }

    public MessageQueue(int size) {
        this.size = size;
        queue = new LinkedBlockingDeque<>(size);
    }

    public static synchronized MessageQueue getInstance() {
        return instance;
    }

    public void push(Object o) {
        synchronized (queue) {  // 调用notify 的地方 锁对象必须存在
            try {
                queue.put(o);
                length++;
            } catch (InterruptedException e) {
                queue.notify();
                e.printStackTrace();
            }
            queue.notify();
        }
    }

    /**
     * 获取当前队列的长度
     * @return
     */
    public long length() {
        return length;
    }

    public Object pop() {
        synchronized (queue) {
            if (length == 0) {
                return null;
            } else {
                length--;
                return queue.poll();
            }
        }
    }
}
